package com.fancon.android.gardenjokesx.activity;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.fancon.android.cache.utils.StorageUtils;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.dialog.ProfilePictureSettingDialog;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.CheckValidate;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;
import com.fancon.android.ui.widget.ImageCacheView;

public class SignupActivity extends GardenJokesBaseActivity {
	private EditText email, username, password, phone;
	private Button btnSignup;
	private ImageCacheView picture;
	private Bundle b;
	private User mUser;
	private int screenId = 0;
	private Boolean isFirst = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_sign_up);
		TextView title = (TextView) findViewById(R.id.action_bar_textview_title);
		title.setText(getText(R.string.signUp));
		View backBtn = findViewById(R.id.action_bar_button_back);
		btnSignup = (Button) findViewById(R.id.signUpButton);
		email = (EditText) findViewById(R.id.email);
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		phone = (EditText) findViewById(R.id.phone);
		picture = (ImageCacheView) findViewById(R.id.fragment_sign_up_imageview);
		// init image
		picture.setImageResource(R.drawable.signup_glyph_avatar);

		b = new Bundle();
		mUser = new User();

		if (getIntent().getExtras() != null) {
			b = getIntent().getExtras();
			if (b.getSerializable("user") != null) {
				mUser = (User) b.getSerializable("user");
			}
			if (b.get(Constant.SCREEN_ID) != null) {
				screenId = b.getInt(Constant.SCREEN_ID);
			}
			
			picture.setPadding(0, 0, 0, 0);
		}
		// Get twitter user information.
		if (screenId == Constant.S03_1) {
			getTwitterUser();
		}

		// Get facebook user information.
		if (screenId == Constant.S03_2) {
			getFacebookUser();
		}
		if (mUser != null) {
			if (mUser.getEmail() != null && mUser.getEmail().length() > 0) {
				email.setText(mUser.getEmail());
			}
			if (mUser.getUser_name() != null
					&& mUser.getUser_name().length() > 0) {
				username.setText(mUser.getUser_name());
			}
			if (mUser.getPassword() != null && mUser.getPassword().length() > 0) {
				password.setText(mUser.getPassword());
			}
			if (mUser.getPhone() != null && mUser.getPhone().length() > 0) {
				phone.setText(mUser.getPhone());
			}
			// for select from gallery and take picture
			if (screenId != Constant.S03_1 && screenId != Constant.S03_2) {
				if (mUser.getUrl_image() != null
						&& mUser.getUrl_image().length() > 0) {
					// set profile picture url.
					Bitmap bm;
					if (mUser.getUrl_image().equalsIgnoreCase("drawable")) {
						bm = BitmapFactory.decodeResource(getResources(),
								R.drawable.common_default_avatar);
					} else {
						bm = BitmapFactory.decodeFile(mUser.getUrl_image());
					}
					picture.setTag(mUser.getUrl_image());
					picture.setImageBitmap(bm);
				}
			}
		}

		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		btnSignup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Checkvalidate()) {
					saveUserInfor();
					JokesRequest signupRequest = new JokesRequest("signup",
							SignupActivity.this);
					getGlobalState().getRequestQueue().addRequest(signupRequest);
				}
			}
		});
		picture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				saveUserInfor();
				b.putInt(Constant.SCREEN_ID, Constant.S01);
				b.putSerializable("user", mUser);
				Dialog settingPicture = new ProfilePictureSettingDialog(
						SignupActivity.this, b);
				settingPicture.show();
			}
		});
	}

	/**
	 * Save user information into User entity object
	 */
	private void saveUserInfor() {
		mUser.setEmail(email.getText().toString());
		mUser.setUser_name(username.getText().toString());
		mUser.setPassword(password.getText().toString());
		mUser.setPhone(phone.getText().toString());
		if (picture.getTag() != null) {
			Log.d("S01", "image url: " + picture.getTag().toString());
			mUser.setUrl_image(picture.getTag().toString());
		} else {
			mUser.setUrl_image("drawable");
		}
	}

	/**
	 * Get Twitter user email, profile picture
	 */
	public void getTwitterUser() {
		
		String token = "", secret = "";
		if (b.getString(Constant.TWITTER_ACCESS_TOKEN) != null) {
			token = b.getString(Constant.TWITTER_ACCESS_TOKEN);
			secret = b.getString(Constant.ACCESS_SECRET);
		}

		SocialUntil social = new SocialUntil(this);
		String profilePictureUrl = social.getImageProfile(token, secret);
		//for get avatar
		picture.loadImage(profilePictureUrl);
		mUser.setUrl_image(StorageUtils.getIndividualCacheDirectory(
				this).getAbsolutePath()+ "/" +profilePictureUrl.hashCode());
		if (b.get(Constant.PRE_SCREEN_ID) == null) {
			mUser.setUser_name(b.getString(Constant.USERNAME_SOCIAL));
			//mUser.setUrl_image(profilePictureUrl);
			if (b.getString(Constant.ABOUT) != null
					&& !"null".equalsIgnoreCase(b.getString(Constant.ABOUT))) {
				mUser.setAbout(StringUtil.validString(
						b.getString(Constant.ABOUT), 147));
				Log.d("S01", "about: " + b.getString(Constant.ABOUT));
			}
		} else if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.S01) {
			//mUser.setUrl_image(profilePictureUrl);
		}
	}

	/**
	 * Get Facebook user email, username, first_name, last name, profile
	 * picture.
	 */
	public void getFacebookUser() {
		
		SocialUntil social = new SocialUntil(this);
		User userFb = social.userInfoFB(b
				.getString(Constant.FACEBOOK_ACCESS_TOKEN));
		b.putString("fb_username", userFb.getUser_name());
		b.putString("fb_userID", userFb.getFacebook_id());

		mUser.setLatitude(userFb.getLatitude());
		mUser.setLongitude(userFb.getLongitude());
		// @binhbt added
		if (b.get(Constant.PRE_SCREEN_ID) == null) {
			if (userFb.getUrl_image() != null) {
				mUser.setUrl_image(StorageUtils.getIndividualCacheDirectory(
						this).getAbsolutePath()
						+ "/" + userFb.getUrl_image().hashCode());
				picture.setTag(mUser.getUrl_image());
				picture.loadImage(userFb.getUrl_image());
			}
			if (userFb.getUser_name() != null) {
				b.putString("fb_username", userFb.getUser_name());
				b.putString("fb_userID", userFb.getUser_id());
				mUser.setUser_name(userFb.getUser_name());
			}
			if (userFb.getFirst_name() != null) {
				mUser.setFirst_name(userFb.getFirst_name());
			}
			if (userFb.getLast_name() != null) {
				mUser.setLast_name(userFb.getLast_name());
			}
			if (userFb.getEmail() != null) {
				mUser.setEmail(userFb.getEmail());
			}
			// Location
			if (userFb.getCurrent_country() != null) {
				mUser.setCurrent_country(userFb.getCurrent_country());
			}
			String city = userFb.getCurrent_city();
			if (city != null) {
				if (userFb.getCurrent_country() != null) {
					try {
						city = URLDecoder.decode(city, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					int index = city.lastIndexOf(",");
					if (index != -1) {
						city = city.substring(0, index);
						mUser.setCurrent_city(city);
					}
				}
			}

		} else if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.S01) {
			if (userFb.getUrl_image() != null) {
				mUser.setUrl_image(StorageUtils.getIndividualCacheDirectory(
						this).getAbsolutePath()
						+ "/" + userFb.getUrl_image().hashCode());
				picture.setTag(mUser.getUrl_image());
				picture.loadImage(userFb.getUrl_image());
			}
		}
	}

	/**
	 * Check data validate
	 * 
	 * @return true or false
	 */
	public Boolean Checkvalidate() {
		String inputEmail = this.email.getText().toString();
		String inputUsername = this.username.getText().toString();
		String inputPassword = this.password.getText().toString();
		//String inputPhoneNumber = this.phone.getText().toString();

		// Check email
		if (inputEmail.length() == 0) {
			showErrorDialog(getString(R.string.ERR5001,
					getString(R.string.email)));
			email.requestFocus();
			return false;
		}
		if (inputEmail.length() > 150) {
			showErrorDialog(getString(R.string.ERR5003,
					getString(R.string.email), "150"));
			email.requestFocus();
			return false;
		}
		if (!CheckValidate.checkEmailFormat(inputEmail)) {
			showErrorDialog(getString(R.string.ERR5005,
					getString(R.string.email)));
			email.requestFocus();
			return false;
		}
		// Check username
		if (inputUsername.length() == 0) {
			showErrorDialog(getString(R.string.ERR5001,
					getString(R.string.username)));
			username.requestFocus();
			return false;
		}
		if (inputUsername.length() > 16) {
			showErrorDialog(getString(R.string.ERR5003,
					getString(R.string.username), "16"));
			username.requestFocus();
			return false;
		}
		if (inputUsername.length() < 4) {
			showErrorDialog(getString(R.string.ERR5002,
					getString(R.string.username), "4"));
			username.requestFocus();
			return false;
		}
		if (!CheckValidate.checkAlphabetOrNumber(inputUsername)) {
			showErrorDialog(getString(R.string.ERR5004,
					getString(R.string.username)));
			username.requestFocus();
			return false;
		}
		// Check password
		if (inputPassword.length() == 0) {
			showErrorDialog(getString(R.string.ERR5001,
					getString(R.string.password)));
			password.requestFocus();
			return false;
		}
		if (inputPassword.length() > 16) {
			showErrorDialog(getString(R.string.ERR5003,
					getString(R.string.password), "16"));
			password.requestFocus();
			return false;
		}
		if (inputPassword.length() < 4) {
			showErrorDialog(getString(R.string.ERR5002,
					getString(R.string.password), "4"));
			password.requestFocus();
			return false;
		}
		if (!CheckValidate.checkAlphabetOrNumber(inputPassword)) {
			showErrorDialog(getString(R.string.ERR5004,
					getString(R.string.password)));
			password.requestFocus();
			return false;
		}

		return true;
	}

	/**
	 * Show dialog when validate is false
	 * 
	 * @param msg
	 */
	public void showErrorDialog(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(true)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						// InputMethodManager inputManager = null;
						// inputManager = (InputMethodManager)
						// SignupActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
						// inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,
						// 1);
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	/**
	 * Finish signup activity
	 */
	public void finishSignUpActivity() {
		finish();
	}

	class JokesRequest extends RequestUI {
		private Activity context;
		private FanconProgressBar progress;
		String result = null;

		public JokesRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context,
						context.getString(R.string.loading));
			}
		}

		@Override
		public void execute() throws Exception {
			Log.d("signup", "signup");
			result = execPost();
			Log.d("signup", result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			if (progress != null) {
				progress.dismiss();
			}
			if (result != null) {
				try {
					JSONObject jObject = new JSONObject(result);
					Boolean isSuccess = jObject.getBoolean("is_success");
					if (isSuccess) {
						// If success => remember to Preference and go to main Page
						String userId = jObject.getString("user_id");
						SharedPreferences settings = getSharedPreferences(
								Constant.PREFS_NAME, 0);
						SharedPreferences.Editor edit = settings.edit();
						edit.putString(Constant.USER_NAME, mUser.getUser_name());
						edit.putString(Constant.PASS, mUser.getPassword());
//						edit.putString(Constant.URL_IMAGE,mUser.);
						edit.putString(Constant.USER_ID_LOGIN, userId);
						edit.putBoolean(Constant.IS_PRIVATE, false);
						edit.commit();
						Intent intent = new Intent(context, GardenJokesActivity.class);
						startActivity(intent);
						finish();
					} else {
						// If fail => show error dialog
						if (jObject.getString("message").equals("API-ERR-S0001")) {
							showErrorDialog("Email already exist");
						} else if (jObject.getString("message").equals("API-ERR-S0002")) {
							showErrorDialog("Username already exist");
						}
						
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}

	}

	/**
	 * SignUP
	 * 
	 * @return
	 */
	private String execPost() {
		MultipartEntity reqEntity = new MultipartEntity();

		Bitmap bm;
		if (mUser.getUrl_image().equalsIgnoreCase("drawable")) {
			bm = BitmapFactory.decodeResource(getResources(),
					R.drawable.common_default_avatar);
		} else {
			try {
				bm = BitmapFactory.decodeFile(mUser.getUrl_image());
			} catch (Exception e) {
				bm = BitmapFactory.decodeResource(getResources(),
						R.drawable.common_default_avatar);
			}
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bm.compress(CompressFormat.JPEG, 75, bos);
		byte[] data = bos.toByteArray();
		ByteArrayBody bad = new ByteArrayBody(data, "avatar.jpg");

		try {
			reqEntity.addPart("image", bad);
			reqEntity
					.addPart("user_name", new StringBody(mUser.getUser_name()));
			reqEntity.addPart("password",
					new StringBody(StringUtil.md5(mUser.getPassword())));
			reqEntity.addPart("email", new StringBody(mUser.getEmail()));
			reqEntity.addPart("phone", new StringBody(mUser.getPhone()));
			reqEntity.addPart("model", new StringBody(Build.MODEL));
			reqEntity.addPart("last_name", new StringBody(""));
			reqEntity.addPart("first_name", new StringBody(""));
			SharedPreferences sett = getSharedPreferences(Constant.PREFS_NAME, 0);
			String token = sett.getString(Constant.REGISTRATION_ID, "null");
			reqEntity.addPart("device_token", new StringBody(token));
			Log.wtf("device token", token);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Log.d("URL", mUser.getUser_name());
		GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
				SignupActivity.this);
		return apiConnect.execPostImg(SignupActivity.this,
				GardenJokesApiConnect.GROUP_S, "signUp", reqEntity);

	}

}
